//
//  RouteHistoryViewController.m
//  leo
//
//  Created by 张旭 on 15/10/21.
//  Copyright © 2015年 mdx. All rights reserved.
//

#import "RouteHistoryViewController.h"
#import "RouteHistoryAnnotationView.h"
#import "LocationPointAnnotation.h"
#import "RangeSlider.h"
#import "CalendarViewController.h"

#define LOG_TAG @"RouteHistoryViewController"

@interface RouteHistoryViewController () {
    RangeSlider *slider;
    
    // StartPoint and DestinationPoint for annotation
    LocationPointAnnotation *startPoint;
    LocationPointAnnotation *destinationPoint;
    
    // An array for save all the path polyline
    NSArray *pathPolylines;
    
    // Use for save all the point which will show on the screen
    NSMutableArray *pathPoint;
    
    // For save the (latitude, longitude) and gen_time
    CLLocationCoordinate2D *coordinates;
    NSInteger *pointTime;
    
    // An MutableArray for save the data get from Database
    NSMutableArray *resultItemArray;
    // The number of the point read from the Database
    NSInteger countOfItems;
    
    NSDate *today;
}

@property (nonatomic, strong) DataManager *dataManager;
@property (nonatomic, strong) SyncManager *syncManager;
@property (nonatomic, retain) AppDelegate *mydelegate;
@property (nonatomic, retain) User        *user;
@property (nonatomic, retain) Watch       *selectWatch;

@end

@implementation RouteHistoryViewController

@synthesize mTodayButton;
@synthesize mLastDayButton;
@synthesize mNextDayButton;
@synthesize mSliderBarView;
@synthesize mMenuView;

-(void)dealloc {
    self.dataManager = NULL;
    self.syncManager = NULL;
    self.mydelegate  = NULL;
    self.user        = NULL;
    self.selectWatch = NULL;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initNavButton];
    [self initDataProxy];
    [self registerObservers];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self initSliderBar];
    [self initSubMapView];
    [self initButtonActions];
    [self.view bringSubviewToFront:mMenuView];
    [self.view bringSubviewToFront:mSliderBarView];
    [self.syncManager getMotionTrack:self.selectWatch.deviceUid withStartTime:@"null" andEndTime:@"null" completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if (result == SUCESS) {
            NSLog(@"%@: Sync from Server successfully.", LOG_TAG);
            
            if ([NO_DATA isEqualToString:description]) {
                [LeoMsg showToastMsg:@"当前设备无这天的轨迹信息" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:SYNCMOTIONTRACKDATAFINISHED object:nil  userInfo:nil];
            }
        }else{
            NSLog(@"%@: Sync from Server failure.", LOG_TAG);
            if(result==NODATA)
            {
               [LeoMsg showToastMsg:@"当前网络异常，请检查网络" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }
            else
            {
                if(description!=NULL)
                    [LeoMsg showToastMsg:description parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }

        }
        
    }];
    
    // Forbid go back by right slip
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    self.search = self.mydelegate.search;
    self.mapView = self.mydelegate.mapView;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    [self clearMapView];
    [self removeObservers];
    [slider removeFromSuperview];
    
    // Enable go back by right slip
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)initDataProxy {
    self.mydelegate = [[UIApplication sharedApplication] delegate];
    NSDate *date = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    today = [date dateByAddingTimeInterval:interval];
    pathPoint = [[NSMutableArray alloc]init];
    self.dataManager = [[DataManager alloc] init];
    self.syncManager = [[SyncManager alloc] init];
    self.user = [User sharedSingleton];
    self.selectWatch = [self.dataManager getActiveWatch:self.user.uid];
}

- (void)clearMapView {
    self.mapView.showsUserLocation = NO;
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    self.mapView.delegate = nil;
    [self.mapView setCompassImage:nil];
    NSLog(@"%@: clearMapView().", LOG_TAG);
}

- (void)initSubMapView {
    CGRect rect = [UIScreen mainScreen].bounds;
    [self.mapView setFrame:CGRectMake(0, 20+44+44, rect.size.width, rect.size.height-(20+44+44+44))];
    self.mapView.showsCompass = NO;
    [self.mapView setRotateEnabled:NO];
    [self.mapView setZoomLevel:15 animated:YES];
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.952136, 116.50095)animated:YES];
}


//UI更改
- (void)initSliderBar {
 
    CGFloat currentTime = [self getCurrentTime];
    
    CGRect rect = [UIScreen mainScreen].bounds;
    NSLog(@"%@: initSliderBar(): %f", LOG_TAG, rect.size.height);
    slider =  [[RangeSlider alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, 44)];
    slider.minimumValue = 0;
    slider.selectedMinimumValue = 0;
    slider.maximumValue = 24;
    slider.selectedMaximumValue = currentTime;
    slider.minimumRange = 0;
    slider.currentTime = currentTime;
    [slider addTarget:self action:@selector(updateRangeLabel:) forControlEvents:UIControlEventValueChanged];
    [mSliderBarView addSubview:slider];


    _endTimeLabel.text = [NSString stringWithFormat:@"%.0f:%.0f",[Tooler getCurrentHour], [Tooler getCurrentMinutes]];
}

- (void)updateRangeLabel:(RangeSlider *)mslider {
    // NSLog(@"%@: Slider Range: %f - %f", LOG_TAG, mslider.selectedMinimumValue, mslider.selectedMaximumValue);
    int hour, minute, second;
    int minTime, maxTime;
    hour = mslider.selectedMinimumValue;
    minute = (mslider.selectedMinimumValue - hour) * 60;
    second = (mslider.selectedMinimumValue - hour) * 3600 - minute * 60;
    minTime = hour * 10000 + minute * 100 + second;
    
    hour = mslider.selectedMaximumValue;
    minute = (mslider.selectedMaximumValue - hour) * 60;
    second = (mslider.selectedMaximumValue - hour) * 3600 - minute * 60;
    maxTime = hour * 10000 + minute * 100 + second;
    
    NSLog(@"%@: Slider Range: %d - %d", LOG_TAG, minTime, maxTime);
    
    [self getLocationInfoFrom:minTime to:maxTime onDate:today];
}

- (void)resetSliderBar:(BOOL)istoday
{
    slider.selectedMinimumValue = 0;
    slider.selectedMaximumValue = 24;
    self.startTimeLabel.text = @"00:00";
    self.endTimeLabel.text = @"24:00";
    //    [slider setNeedsFocusUpdate];
    //    [slider setNeedsDisplay];
    if (istoday) {
        slider.selectedMaximumValue = [self getCurrentTime];
        _endTimeLabel.text = [NSString stringWithFormat:@"%.0f:%.0f",[Tooler getCurrentHour], [Tooler getCurrentMinutes]];
    }
  
    [slider setNeedsLayout];
}

- (void)initButtonActions {
    [mTodayButton addTarget:self action:@selector(showCalendar) forControlEvents:UIControlEventTouchUpInside];
    [mLastDayButton addTarget:self action:@selector(yesterday) forControlEvents:UIControlEventTouchUpInside];
    [mNextDayButton addTarget:self action:@selector(tomorrow) forControlEvents:UIControlEventTouchUpInside];
}

- (void)showCalendar {
    //    CalendarViewController *calendarViewController = [[CalendarViewController alloc]init];
    //    [self.navigationController pushViewController:calendarViewController animated:YES];
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    CalendarViewController *calendarViewController = [[CalendarViewController alloc]init];
    [calendarViewController setMotherWindow:alertView];
    [calendarViewController setDateSelected:today];
    alertView.rootViewController = calendarViewController;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
}

- (void)initNavButton {
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title = @"轨迹";
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
    [self clearMapView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self removeObservers];
    // Dispose of any resources that can be recreated.
    if(self.view.window == nil)
    {
        self.view = nil;
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)getLocationInfoFrom:(int)min to:(int)max onDate:(NSDate *)date {
    NSArray *tmpArray;
    NSInteger i, j;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLog(@"RouteView map delegate = %@",self.mapView.delegate);
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *startTimeString = [[dateFormatter stringFromDate:date] stringByAppendingString:@" 00:00:00"];
    NSString *endTimeString = [[dateFormatter stringFromDate:date] stringByAppendingString:@" 23:59:59"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@: The time now is %@", LOG_TAG, [dateFormatter stringFromDate:date]);
    NSLog(@"%@: startTimeString: %@", LOG_TAG, startTimeString);
    NSLog(@"%@: endTimeString: %@", LOG_TAG, endTimeString);
    
    NSString *startTime = [Tooler strToTime:startTimeString];
    NSString *endTime = [Tooler strToTime:endTimeString];
    NSLog(@"%@: startTime = %@", LOG_TAG, startTime);
    NSLog(@"%@: endTime = %@", LOG_TAG, endTime);
    
    // Get all the datas of one day from Database
    tmpArray = [self.dataManager getLocationList:self.selectWatch.deviceUid startTime:startTime endTime:endTime];
    countOfItems = [tmpArray count];
    NSLog(@"%@: There are %lu items get from Database.", LOG_TAG, [tmpArray count]);
    
    coordinates = (CLLocationCoordinate2D *)malloc(countOfItems * sizeof(CLLocationCoordinate2D));
    pointTime = (NSInteger *)malloc(countOfItems * sizeof(NSInteger));
    resultItemArray = [[NSMutableArray alloc] init];
    
    i = j = 0;
    [dateFormatter setDateFormat:@"HHmmss"];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    for(Location *obj in tmpArray) {
        if (i != 0 && obj.latitude == coordinates[i - 1].latitude && obj.longtitude == coordinates[i - 1].longitude) {
            NSLog(@"%@: Debug for TianAnMen, %f, %f, %@, %@, %@. When i == %li ---> But it is removed.", LOG_TAG, obj.latitude, obj.longtitude, obj.mainAddress, obj.subAddress, obj.gen_time, (long)j);
        } else {
            coordinates[i].latitude = obj.latitude;
            coordinates[i].longitude = obj.longtitude;
            pointTime[i] = [[dateFormatter stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:[obj.gen_time doubleValue]]] intValue];
            
            NSLog(@"%@: Debug for TianAnMen, %f, %f, %@, %@, %@. When i == %li.", LOG_TAG, obj.latitude, obj.longtitude, obj.mainAddress, obj.subAddress, obj.gen_time, (long)j);
            
            [resultItemArray addObject:obj];
            
            i++;
        }
        
        j++;
    }
    
    countOfItems = i;
    NSLog(@"%@: After Filter, there left %lu items in resultItemArray.", LOG_TAG, countOfItems);
    
    // Get the time later than min and earlier than max(the data items we need show on screen)
    for (i = 0; i < countOfItems; i++) {
        if(pointTime[i] >= min)
            break;
    }
    
    for (j = countOfItems - 1; j >= 0; j--) {
        if (pointTime[j] <= max) {
            break;
        }
    }
    
    // Calculate the time for startTimeLabel and endTimeLabel under Slider
    NSString *minHourStr = [[[NSString alloc] initWithFormat:@"%d", (min / 10000)] stringByAppendingString:@":"];
    NSString *maxHourStr = [[[NSString alloc] initWithFormat:@"%d", (max / 10000)] stringByAppendingString:@":"];
    NSString *minMinuteStr = [[NSString alloc] initWithFormat:@"%d", ((min / 100) % 100)];
    NSString *maxMinuteStr = [[NSString alloc] initWithFormat:@"%d", ((max / 100) % 100)];
    
    if ((min / 10000) < 10) {
        minHourStr = [@"0" stringByAppendingString:minHourStr];
    }
    if ((max / 10000) < 10) {
        maxHourStr = [@"0" stringByAppendingString:maxHourStr];
    }
    if (((min / 100) % 100) < 10) {
        minMinuteStr = [@"0" stringByAppendingString:minMinuteStr];
    }
    if (((max / 100) % 100) < 10) {
        maxMinuteStr = [@"0" stringByAppendingString:maxMinuteStr];
    }
    
    self.startTimeLabel.text = [minHourStr stringByAppendingString:minMinuteStr];
    self.endTimeLabel.text = [maxHourStr stringByAppendingString:maxMinuteStr];
    
    // if there has some point later than min and earlier than max, show them
    if ((j - i + 1) != 0) {
        [self annotationForKeyPointFrom:i to:j];
        pathPolylines = [self polylinesForPath:&coordinates[i] count:(j - i + 1)];
        [self.mapView addOverlays:pathPolylines];
        // [self.mapView showAnnotations:@[destinationPoint, startPoint] animated:YES];
    } else {
        if (startPoint != nil) {
            [self.mapView removeAnnotation:startPoint];
            startPoint = nil;
        }
        if (destinationPoint != nil) {
            [self.mapView removeAnnotation:destinationPoint];
            destinationPoint = nil;
        }
        [self.mapView removeAnnotations:pathPoint];
        [pathPoint removeAllObjects];
        if (pathPolylines != nil) {
            [self.mapView removeOverlays:pathPolylines];
            pathPolylines = nil;
        }
    }
    
    free(coordinates), coordinates = NULL;
    free(pointTime), pointTime = NULL;
}

//use for all direction
- (void)annotationForKeyPointFrom:(NSInteger)begin to:(NSInteger)end {
    double deltaX;
    double deltaY;
    double slope;
    double radian = 0.0;
    
    if (startPoint != nil) {
        [self.mapView removeAnnotation:startPoint];
        startPoint = nil;
    }
    
    if (destinationPoint != nil) {
        [self.mapView removeAnnotation:destinationPoint];
        destinationPoint = nil;
    }
    
    [self.mapView removeAnnotations:pathPoint];
    [pathPoint removeAllObjects];
    
    Location *startLoc = [resultItemArray objectAtIndex:begin];
    CLLocationCoordinate2D startCoordinate;
    startCoordinate.latitude = startLoc.latitude;
    startCoordinate.longitude = startLoc.longtitude;
    startPoint = [[LocationPointAnnotation alloc] init];
    startPoint.location = startLoc;
    startPoint.coordinate = startCoordinate;
    startPoint.radian = @"0";
    
    [pathPoint addObject:startPoint];
    
    Location *destLoc = [resultItemArray objectAtIndex:end];
    CLLocationCoordinate2D destCoordinate;
    destCoordinate.latitude = destLoc.latitude;
    destCoordinate.longitude = destLoc.longtitude;
    destinationPoint = [[LocationPointAnnotation alloc] init];
    destinationPoint.location = destLoc;
    destinationPoint.coordinate = destCoordinate;
    destinationPoint.radian = @"0";
    [pathPoint addObject:destinationPoint];
    
    //for (int i = 2; i < count - 2; i += 2) {
    //for (NSInteger i = begin + 2; i < end - 1; i += 2) {
    for (NSInteger i = begin + 1; i < end; i += 1) {
        Location *directionLoc = [resultItemArray objectAtIndex:i];
        CLLocationCoordinate2D directionCoordinate;
        directionCoordinate.latitude = directionLoc.latitude;
        directionCoordinate.longitude = directionLoc.longtitude;
        Location *nextLoc = [resultItemArray objectAtIndex:i + 1];
        LocationPointAnnotation *directionAnnotation = [[LocationPointAnnotation alloc] init];
        directionAnnotation.location = directionLoc;
        directionAnnotation.coordinate = directionCoordinate;
        
        deltaX = nextLoc.longtitude - directionAnnotation.coordinate.longitude;
        deltaY = nextLoc.latitude - directionAnnotation.coordinate.latitude;
        
        if (deltaX == 0)
            slope = MAXFLOAT;
        else
            slope = deltaY / deltaX;
        //NSLog(@"slope[%d] equals: %f", i, slope);
        
        if (slope == MAXFLOAT) {
            if (deltaY < 0) {
                radian = M_PI / 2;
            } else {
                radian = -(M_PI / 2);
            }
        } else if (slope == 0) {
            if (deltaX < 0) {
                radian = M_PI;
            } else {
                radian = 0;
            }
        } else if (slope < 0) {
            if (deltaX > 0) {
                radian = -atan(slope);
            } else {
                radian = -(M_PI + atan(slope));
            }
        } else if (slope > 0) {
            if (deltaX > 0) {
                radian = -atan(slope);
            } else {
                radian = M_PI - atan(slope);
            }
        }
        
        directionAnnotation.radian = [NSString stringWithFormat:@"%f", radian];
        //NSLog(@"slope in NSString equals: %@", directionAnnotation.title);
        
        [pathPoint addObject:directionAnnotation];
    }
    
    [self.mapView showAnnotations:pathPoint animated:YES];
    [self.mapView addAnnotations:pathPoint];
    //    [self.mapView addAnnotation:destinationPoint];
    //    [self.mapView addAnnotation:startPoint];
}

- (NSArray *)polylinesForPath:(CLLocationCoordinate2D *)path count:(NSInteger)count {
    if (pathPolylines != nil) {
        [self.mapView removeOverlays:pathPolylines];
        pathPolylines = nil;
    }
    
    NSMutableArray *polylines = [NSMutableArray array];
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:path count:count];
    [polylines addObject:polyline];
    //free(path), path = NULL;
    
    return polylines;
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        polylineView.lineWidth   = 4;
        polylineView.strokeColor = [UIColor colorWithRed:0.17 green:0.59 blue:1 alpha:1];
        return polylineView;
    }
    
    NSLog(@"%@: The type of overlay is %@.", LOG_TAG, [overlay class]);
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[LocationPointAnnotation class]]) {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        RouteHistoryAnnotationView *annotationView = (RouteHistoryAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[RouteHistoryAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        
        // must set to NO, so we can show the custom callout view.
        annotationView.canShowCallout   = NO;
        annotationView.draggable        = NO;
        annotationView.calloutOffset    = CGPointMake(0, 0);
        LocationPointAnnotation *locationPointAnnotation = annotation;
        
        // Choose the image of different point
        if (annotation == startPoint) {
            annotationView.portrait = [UIImage imageNamed:@"history_setstart_@2x"];
        } else if (annotation == destinationPoint) {
            annotationView.portrait = [UIImage imageNamed:@"history_setend_@2x"];
        } else {
            annotationView.portrait = [UIImage imageNamed:@"history_Arrow_right@2x"];
        }
        
        // Set the main and sub label
        annotationView.mainLabelValue = locationPointAnnotation.location.mainAddress;
        annotationView.subLabelValue = locationPointAnnotation.location.subAddress;
        
        // Judge the location method
        if (locationPointAnnotation.location.locateType == 0) {
            annotationView.locateTypeLabelValue = @"GPS定位";
        } else if (locationPointAnnotation.location.locateType == 1) {
            annotationView.locateTypeLabelValue = @"网络定位";
        } else if (locationPointAnnotation.location.locateType == 2) {
            annotationView.locateTypeLabelValue = @"网络定位";
        }
        
        // Set the radius label
        annotationView.radiusLabelValue = [NSString stringWithFormat:@"%d", (int)locationPointAnnotation.location.radius];
        
        // Judge the location type
        if (locationPointAnnotation.location.type == 0) {
            annotationView.typeLabelValue = @"定时定位";
        } else if (locationPointAnnotation.location.type == 1) {
            annotationView.typeLabelValue = @"紧急定位";
        } else if (locationPointAnnotation.location.type == 2) {
            annotationView.typeLabelValue = @"蓝牙定位";
        } else if (locationPointAnnotation.location.type == 3) {
            annotationView.typeLabelValue = @"低电定位";
        } else if (locationPointAnnotation.location.type == 4){
            annotationView.typeLabelValue = @"立即定位";
        } else if (locationPointAnnotation.location.type == 5){
            annotationView.typeLabelValue = @"开机定位";
        }
        
        // Set the date label
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM-dd HH:mm"];
        [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
        NSString *_gen_time = [dateFormatter stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:[locationPointAnnotation.location.gen_time doubleValue]]];
        annotationView.dateLabelValue = _gen_time;
        
        // Set the radian value
        annotationView.radian = locationPointAnnotation.radian;
        
        return annotationView;
    }
    
    NSLog(@"%@: The type of annotation is %@.", LOG_TAG, [annotation class]);
    return nil;
}

- (void)yesterday {
    NSTimeInterval a_day = 24*60*60;
    today = [NSDate dateWithTimeInterval:(-a_day) sinceDate:today];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"utc"]];
    //[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *syncStartTime = [[dateFormatter stringFromDate:today] stringByAppendingString:@" 00:00:00"];
    NSString *syncEndTime = [[dateFormatter stringFromDate:today] stringByAppendingString:@" 23:59:59"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@: syncNowTime is %@", LOG_TAG, [dateFormatter stringFromDate:today]);
    NSLog(@"%@: syncStartTime is %@", LOG_TAG, syncStartTime);
    NSLog(@"%@: syncEndTime is %@", LOG_TAG, syncEndTime);
    
    [dateFormatter setDateFormat:@"yyyy"];
    int year = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"MM"];
    int month = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"dd"];
    int day = [[dateFormatter stringFromDate:today] intValue];
    
    if ([self isToday:[dateFormatter stringFromDate:today]]) {
        [mTodayButton setTitle:@"今天" forState:UIControlStateNormal];
         [self resetSliderBar:YES];
    } else {
         [self resetSliderBar:NO];
        [mTodayButton setTitle:[NSString stringWithFormat:@"%d月%d日", month, day]forState:UIControlStateNormal];
    }
    
   
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    
    NSArray *haveEvent = [self.dataManager getMonthLocData:year month:month deviceUid:self.selectWatch.deviceUid];
    
    if ([haveEvent[day] isEqualToString:@"0"]) {
        [self.syncManager getMotionTrack:self.selectWatch.deviceUid withStartTime:syncStartTime andEndTime:syncEndTime completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if (result == SUCESS) {
                if ([NO_DATA isEqualToString:description]) {
                    [LeoMsg showToastMsg:@"当前设备无这天的轨迹信息" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
                } else {
                    [[NSNotificationCenter defaultCenter] postNotificationName:SYNCDATAINROUTEHISTORYVIEW object:nil userInfo:nil];
                }
            } else {
                if ([self isNullValue:description]) {
                    description = @"服务器异常";
                }
                
                [LeoMsg showToastMsg:description parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }
        }];
    } else {
        [self getLocationInfoFrom:0 to:240000 onDate:today];
        
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSLog(@"%@: No Need Sync! The value of today now is: %@", LOG_TAG, [dateFormatter stringFromDate:today]);
    }
}

//UI更改
- (void)tomorrow {
 
    if ([self isRealToday:today]) {
//        mNextDayButton.enabled = NO;
        return;
    }
    mNextDayButton.enabled = YES;
    NSTimeInterval a_day = 24*60*60;
    today = [NSDate dateWithTimeInterval:a_day sinceDate:today];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"utc"]];
    //[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *syncStartTime = [[dateFormatter stringFromDate:today] stringByAppendingString:@" 00:00:00"];
    NSString *syncEndTime = [[dateFormatter stringFromDate:today] stringByAppendingString:@" 23:59:59"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@: syncNowTime is %@", LOG_TAG, [dateFormatter stringFromDate:today]);
    NSLog(@"%@: syncStartTime is %@", LOG_TAG, syncStartTime);
    NSLog(@"%@: syncEndTime is %@", LOG_TAG, syncEndTime);
    
    [dateFormatter setDateFormat:@"yyyy"];
    int year = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"MM"];
    int month = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"dd"];
    int day = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    if ([self isToday:[dateFormatter stringFromDate:today]]) {
        [mTodayButton setTitle:@"今天" forState:UIControlStateNormal];
        [self resetSliderBar:YES];
    } else {
        [self resetSliderBar:NO];
        [mTodayButton setTitle:[NSString stringWithFormat:@"%d月%d日", month, day]forState:UIControlStateNormal];
    }
    

    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    
    NSArray *haveEvent = [self.dataManager getMonthLocData:year month:month deviceUid:self.selectWatch.deviceUid];
    
    if ([haveEvent[day] isEqualToString:@"0"]) {
        [self.syncManager getMotionTrack:self.selectWatch.deviceUid withStartTime:syncStartTime andEndTime:syncEndTime completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if (result == SUCESS) {
                if ([NO_DATA isEqualToString:description]) {
                    [LeoMsg showToastMsg:@"当前设备无这天的轨迹信息" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
                } else {
                    [[NSNotificationCenter defaultCenter] postNotificationName:SYNCDATAINROUTEHISTORYVIEW object:nil userInfo:nil];
                }
            } else {
                if ([self isNullValue:description]) {
                    description = @"服务器异常";
                }
                
                [LeoMsg showToastMsg:description parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }
        }];
    } else {
        [self getLocationInfoFrom:0 to:240000 onDate:today];
        
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSLog(@"%@: No Need Sync! The value of today now is: %@", LOG_TAG, [dateFormatter stringFromDate:today]);
    }
}


- (void)renderTodayTrack:(NSNotification *)notification {
    [self getLocationInfoFrom:0 to:240000 onDate:today];
}

- (void)selectDateFromCalendar:(NSNotification *)notification {
    NSDictionary *theData = [notification userInfo];
    today = [theData objectForKey:@"dateSelected"];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"utc"]];
    //[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSLog(@"%@: After format, today is: %@", LOG_TAG, [dateFormatter stringFromDate:today]);
    NSString *syncStartTime = [[dateFormatter stringFromDate:today] stringByAppendingString:@" 00:00:00"];
    NSString *syncEndTime = [[dateFormatter stringFromDate:today] stringByAppendingString:@" 23:59:59"];
    NSLog(@"%@: syncStartTime is %@", LOG_TAG, syncStartTime);
    NSLog(@"%@: syncEndTime is %@", LOG_TAG, syncEndTime);
    
    [dateFormatter setDateFormat:@"yyyy"];
    int year = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"MM"];
    int month = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"dd"];
    int day = [[dateFormatter stringFromDate:today] intValue];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    if ([self isToday:[dateFormatter stringFromDate:today]]) {
        [mTodayButton setTitle:@"今天" forState:UIControlStateNormal];
        [self resetSliderBar:YES];
    } else {
        [self resetSliderBar:NO];
        [mTodayButton setTitle:[NSString stringWithFormat:@"%d月%d日", month, day]forState:UIControlStateNormal];
    }
    
  
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    
    NSArray *haveEvent = [self.dataManager getMonthLocData:year month:month deviceUid:self.selectWatch.deviceUid];
    
    if ([haveEvent[day] isEqualToString:@"0"]) {
        [self.syncManager getMotionTrack:self.selectWatch.deviceUid withStartTime:syncStartTime andEndTime:syncEndTime completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if (result == SUCESS) {
                if ([NO_DATA isEqualToString:description]) {
                    [LeoMsg showToastMsg:@"当前设备无这天的轨迹信息" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
                } else {
                    [[NSNotificationCenter defaultCenter] postNotificationName:SYNCDATAINROUTEHISTORYVIEW object:nil userInfo:nil];
                }
            } else {
                if ([self isNullValue:description]) {
                    description = @"服务器异常";
                }
                
                [LeoMsg showToastMsg:description parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }
            
        }];
    } else {
        [self getLocationInfoFrom:0 to:240000 onDate:today];
        
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSLog(@"%@: No Need Sync! The value of today now is: %@", LOG_TAG, [dateFormatter stringFromDate:today]);
    }
}

- (void)syncDataInRouteHistoryViewController:(NSNotification *)notification {  // 20151231
    [self getLocationInfoFrom:0 to:240000 onDate:today];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"utc"]];
    //[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@: Need Sync! The value of today now is: %@", LOG_TAG, [dateFormatter stringFromDate:today]);
}

- (BOOL)isToday:(NSString *)selectDate {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    
    if ([selectDate isEqualToString:[dateFormatter stringFromDate:date]]) {
        return YES;
    }
    
    return NO;
}

- (void)registerObservers {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(renderTodayTrack:) name:SYNCMOTIONTRACKDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectDateFromCalendar:) name:SELECTDATEFROMCALENDAR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(syncDataInRouteHistoryViewController:) name:SYNCDATAINROUTEHISTORYVIEW object:nil];
    
    NSLog(@"%@: registerObservers.", LOG_TAG);
}

- (void)removeObservers{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SYNCMOTIONTRACKDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SELECTDATEFROMCALENDAR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SYNCDATAINROUTEHISTORYVIEW object:nil];
}

-(BOOL)isNullValue:(NSString *)value {
    if ([@"" isEqualToString:value] || [@"null" isEqualToString:value]
        || [@"(null)" isEqualToString:value] || value == NULL) {
        return YES;
    }
    return NO;
}



//UI更改
- (BOOL)isRealToday:(NSDate *)day
{
    //判断是否是今天
    NSDate *date = [NSDate date];
    //    NSTimeZone *zone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *realToday = [date dateByAddingTimeInterval:interval];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    if ([[formatter stringFromDate:realToday] isEqual:[formatter stringFromDate:day]]) {
//        mNextDayButton.enabled = NO;
        return YES;
    }
    return NO;

}

//UI更改
- (CGFloat)getCurrentTime
{
    CGFloat currentHour= [Tooler getCurrentHour];
    CGFloat currentMinutes = [Tooler getCurrentMinutes];

    CGFloat currentTime = currentHour + 0.01 * currentMinutes * 60 /100;
    return currentTime;
}

@end